package agend.behaviours.one_to_one;

import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import agend.agents.AgendAgent;
import agend.dlv.DlvMaker.TypeOutput;
import dto.utils.DataTransferObject;
import dto.utils.SingleEvent;

public class OneToOneReceiverBehaviour extends Behaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private DataTransferObject dto;
	private ACLMessage reply;
	
	
	private SingleEvent result;
	
	private int step;

	public OneToOneReceiverBehaviour(DataTransferObject dto,ACLMessage message) {

		this.dto = dto;
		reply = message.createReply();
		step = 0;
	}

	@Override
	public void action() {

		// TODO Auto-generated method stub
		switch (step) {

		case 0:
		{	
			List<SingleEvent> myEvents=((AgendAgent)myAgent).getGoogleServices().getEventsByRange(dto.getStartTime(), dto.getEndTime());

			dto.getEvents().addAll(myEvents);

			step = 1;

			break;
		}
		case 1:
		{
			AgendAgent thisAgent = (AgendAgent)myAgent;
			thisAgent.getDlvMaker().setSettings(dto.getStartTime(), dto.getEndTime(), thisAgent.getDisponibilitaSettimanale(), thisAgent.getPeriodiInattivita(), dto.getPreferenza(), dto.getDuration());
			thisAgent.getDlvMaker().crea(dto.getEvents());
			
			step = 2;

			break;
		}
		case 2:
		{
			AgendAgent thisAgent = (AgendAgent)myAgent;
			thisAgent.getDlvMaker().writeFile();
			
			step = 3;
			
			break;
		}
		case 3:
		{
			AgendAgent thisAgent = (AgendAgent)myAgent;
			Object object = thisAgent.getDlvMaker().execute(TypeOutput.ONE_TO_ONE);
			
			if(object instanceof SingleEvent)
				result = (SingleEvent) object;
			else
				result = new SingleEvent();
			
			step = 4;
			
			break;
		}
		case 4:
		{
						
			if(result.isValid())
			
				reply.setPerformative(ACLMessage.ACCEPT_PROPOSAL);
				

			
			else 
				reply.setPerformative(ACLMessage.REJECT_PROPOSAL);
			
			try {
				reply.setContentObject(result);
				myAgent.send(reply);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			step = 5;
				
			break;
		}
		default:
			break;
		}

	}

	@Override
	public boolean done() {
		// TODO Auto-generated method stub
		return (step==5);
	}

}
